<?php
// +----------------------------------------------------------------------
// | Home项目基类
// +----------------------------------------------------------------------
// | Home所有Action都继承此类
// +----------------------------------------------------------------------
// | Author: 李乾坤 <261001642@qq.com>
// +----------------------------------------------------------------------
//import("ORG.Util.Cookie");

namespace app\home\controller;
//use think\View;
use think\Controller;
use ORG\Safe;
class Base extends Controller
{
    function initialize() {
        /*if(Safe::check(true)){
            $this->error('您的提交带有不合法参数,谢谢合作!');
        }*/
        if (!session('?uid')){
            //$loginfo=authcode(Cookie('loginfo'));
            /*if(!empty($loginfo)){
                $loginfo=explode(',',$loginfo);
                Session("uid",   $loginfo[0]);
                Session('nickname',   $loginfo[1]);
                Session('account',   $loginfo[2]);
                if($loginfo[0]=='-1') {{
                    Session('administrator',   true);
                }
            }else{*/
                \Session('uid',Config('GUEST_AUTH_ID'));
                \Session('nickname','游客');
                \Session('account','游客');
            //}
        }
        //$this->navigation();
        $this->readConfig();
    }
    protected function readConfig(){
        $list=Cache('Config');
        if (!$list) {
            $config = model("Config");
            $groups = $config->distinct(true)->column('category');
            $list = array();
            foreach ($groups as $value){
                $_tmp = $config->where('category',$value)->column('name,value');
                $list[$value] = array_change_key_case($_tmp,CASE_LOWER);
            }
            $list=array_change_key_case($list,CASE_LOWER);
            // 所有配置参数统一为大写
            Cache('Config',$list);
        }
        foreach ($list as $key=>$value){
            Config($value,$key);
        }
    }
    protected function navigation(){
        $list=Cache('Navigation');
        if (!$list) {
            $Menu = model('Menu');
            $list = $Menu->fielmodel('id,name,link,title,target')->where('status=1 and level=0')->order('sort asc')->select();
            foreach ($list as $key => $value) {
                $list[$key]['_child']=$Menu->fielmodel('name,link,title,target')->where('status=1 and level=1 and pid='.$value['id'])->order('sort asc')->select();
            }
			$list=array_change_key_case($list,CASE_UPPER);
            Cache('Navigation',$list);
        }
        $this->assign('navigation', $list);
    }
    // 404 错误定向
    function http404($message = '', $jumpUrl = '', $waitSecond = 3) {
        $this->assign('message', '访问的页面不存在！');
        if (!empty($jumpUrl)) {
            $this->assign('jumpUrl', $jumpUrl);
            $this->assign('waitSecond', $waitSecond);
        }
        return view('public:http404');
    }
    /*public function _empty($method) {
        $this->assign('message', '非法操作！');
        return view(config('TMPL_ACTION_ERROR'));
    }*/
    public function _empty($method) {
        return view();
    }
    public function save($model=false,$data=null)
    {
        if (!$model){
            $model=request()->controller();
        }
        $model  =   model($model);
        if (is_null($data)){
            $data=$_POST;
        }
        if($data[$model->getPk()]){
            $map = [];
            $map[$model->getPk()]=$data[$model->getPk()];
            $result = $model->allowField(true)->validate(true)->save($data,$map);
            $model->id = $data['id'];
            echo 'update',$result;
            //echo $model->getlastsql();
        }else{
            $result = $model->validate(true)->allowField(true)->save($data);
            echo 'insert',$result;
        }
        echo $result;
        P($model->id);
        if($result) {
            return $model->id;
        }else {
            return false;
        }
    }
    function postcomment(){
        $Comment=model('Comment');
        if(false === $Comment->create()) {
            $this->error($Comment->getError());
        }
        if($result = $Comment->add()) {
            $this->assign('jumpUrl',$_POST['jumpurl']);
            $this->success('评论成功');
        }else {
            $this->error('评论失败');
        }
    }
    function getcomment(){
        $pid=input('pid');
        $currpage=input('p');
        $module=input('module');
        $model=model('Comment');
        $map="status=1 and module='".$module."' and pid=".$pid;
        $count = $model->where($map)->count('id');
        if ($count > 0) {
            $list = $model->where($map)->order('id desc ')->page($currpage,20)->select();
            foreach ($list as $key => $vo) {
                $blogurl=U('Blog/').$vo['uid'];
                $cui=GUI($vo['uid']);
                $html.='<li><a href="'.$blogurl.'"><img src="'.$cui['avatar'].'" alt="'.$cui['nickname'].'" /></a><a href="'.$blogurl.'" class="green">'.$cui['nickname'].'</a><span class="colorL">'.toDate($vo['create_time'],'Y-m-d H:i:s').'</span><div class="colorD">'.parseemote($vo['content']).'</div></li>';
            }
            $this->success($html);
        }else{
            $this->error('木有内容');
        }
    }
    /**
    * 站点公用上传方法
    * @name  ,表单里所有file的name值,作检测是否需要上传
    * @path,保存路径
    * @thumb,是否缩略图
    * @turnpost,是否自动转换到POST数组,为假就直接返回数组,自己处理,为真就直接当普通字段处理,只不过文件的内容已经换成服务器保存路径了
    * @maxsize,文件最大大小
    * @ext,文件扩展名限制
    */
    protected function _upload($name,$path='./Public/Uploads/',$thumb=false,$turnpost=true,$maxSize=0,$ext='gif,png,jpg,jpeg'){
        if (is_array($name)){
            $tf=false;
            foreach ($name as $k => $v) {
                if (!empty($_FILES[$v]['name'])){
                    $tf=true;
                    break;
                }
            }
            if (!$tf){
                return false;
            }
        }elseif(empty($_FILES[$name]['name'])){
            return false;
        }
        import("ORG.Net.UploadFile");
        $upload = new UploadFile();
        if ($thumb!==false){
            $upload->thumb      =true;
            $size=explode(',', $thumb);
            $upload->thumbMaxWidth =$size[0];
            $upload->thumbMaxHeight =$size[1];
        }
        $upload->maxSize= ($maxSize ==0) ? config('UPLOAD_MAX_SIZE') : $maxSize;
        $upload->allowExts  = explode(',',$ext);
        $upload->savePath =  $path;
        // 记录上传成功ID
        $uploadId =  array();
        $savename = array();
        //执行上传操作
        if(!$upload->upload()) {
            if($this->isAjax() && isset($_POST['_uploadFileResult'])) {
                $uploadSuccess =  false;
                $ajaxMsg  =  $upload->getErrorMsg();
            }else {
                //捕获上传异常
                $this->error($upload->getErrorMsg());
            }
        }else {
             //取得成功上传的文件信息
            $uploadList = $upload->getUploadFileInfo();
            if ($turnpost){
                foreach ($uploadList as $key => $value) {
                    if ($value['array']){
                        $_POST[$value['title']][]=$value['savepath'].$value['savename'];
                    }else{
                        $_POST[$value['title']]=$value['savepath'].$value['savename'];;
                    }
                }
            } else{
                return $uploadList;
            }
        }
    }
    function saveTag($tags, $id, $module = MODULE_NAME) {
        if (!empty($tags) && !empty($id)) {
            $Tag = model("Tag");
            $Tagged = model("Tagged");            // 记录已经存在的标签
            $exists_tags = $Tagged->where("module='{$module}' and record_id={$id}")->column("id,tag_id");
            $Tagged->where("module='{$module}' and record_id={$id}")->delete();
            $tags = explode(' ', $tags);
            foreach ($tags as $key => $val) {
                $val = trim($val);
                if (!empty($val)) {
                    $tag = $Tag->where("module='{$module}' and name='{$val}'")->find();
                    if ($tag) {                        // 标签已经存在
                        if (!in_array($tag['id'], $exists_tags)) {
                            $Tag->where('id=' . $tag['id'])->setInc('count');
                        }
                    } else {                        // 不存在则添加
                        $tag = array();
                        $tag['name'] = $val;
                        $tag['count'] = 1;
                        $tag['module'] = $module;
                        $result = $Tag->save($tag);
                        $tag['id'] = $Tag->id;
                    }                    // 记录tag关联信息
                    $t = array();
                    $t['user_id'] = \think\Session::get(config('USER_AUTH_KEY'));
                    $t['module'] = $module;
                    $t['record_id'] = $id;
                    $t['create_time'] = time();
                    $t['tag_id'] = $tag['id'];
                    $Tagged->save($t);
                }
            }
        }
    }
    public function delete($model=false)
    {
        $this->checkuser();
        if (!$model){
            $model=request()->controller();
        }
        $model  =   model($model);
        if(!empty($model)) {
            $pk =   $model->getPk();
            $id         = input($pk);
            if(isset($id)) {
                $condition = array($pk=>array('in',explode(',',$id)));
                if(false !== $model->where($condition)->delete()){
                    $this->success(L('删除成功'));
                }else {
                    $this->error(L('删除失败'));
                }
            }else {
                $this->error('非法操作');
            }
        }
    }
    function checkuser(){
        if (!$_SESSION['uid'] || $_SESSION['uid']==-2){
            redirect('/login.html');
        }
    }
	function setseoinfo($title='',$kw='',$description='',$addr=array()){
		$keyword 			=	require(\Env::get('config_path').'keyword.php');
        $this->assign('page_title', $title);
        $this->assign('page_keyword', $kw);
        $this->assign('page_description', $description);
	}
	function saveattach(){
		save_attach($_POST);
	}
    function getToken(){
        $type=input('get.type',0,'intval');
        if($type==0){
            $bucket = 'sssui';
            $accessKey = 'FwbFcOniG6Af7osdFaoXepZWY25SxH6fmM1dwXre';
            $secretKey = 'Ym-jNPMMYLLCf13IxuuCC_LkeL9gTDC0pyqbVGyf';
        }elseif($type==1){
            $bucket = 'llxfs';
            $accessKey = 'B3MuF30rKh89-U6HMfbGqmkIKbyU8GqnXwcyJQVL';
            $secretKey = '4w0aHjvf-hEHlk8pVjQjJfKdHdjIkPKSvl-cjQKU';
        }
        Vendor('Qiniu',LIB_PATH.'/Vendor');
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        echo json_encode(array('uptoken'=>$token));
    }
    /*protected function display($templateFile='',$charset='',$contentType='',$content='',$prefix='') {
        $prefix  =  $prefix ? $prefix : (isPjax() ? '' : 'pjax_');
        $this->view->display($templateFile,$charset,$contentType,$content,$prefix);
    }*/
}
